package novel.spider.util;

import novel.spider.NovelSiteEnum;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Kau on 2016/10/30.
 */
public final class NovelSpiderUtil {
    private static final Map<NovelSiteEnum,Map<String, String>> CONTEXT_MAP = new HashMap<>();
    //即运行
    static {
        init();
    }
    //禁止实例化
    private NovelSpiderUtil(){}

    private static void init(){
        SAXReader reader = new SAXReader();
        try {
            //通过配置文件读取
            Document doc = reader.read(new File("src/conf/Spider-Rules.xml"));
            //获取根节点
            Element root = doc.getRootElement();
            List<Element> sites = root.elements("site");
            for (Element site : sites){
                List<Element> subs = site.elements();
                Map<String, String> subMap = new HashMap<>();
                for (Element sub : subs){
                    String name = sub.getName();
                    String text = sub.getTextTrim();
                    subMap.put(name, text);
                }
                CONTEXT_MAP.put(NovelSiteEnum.GetEnumByUrl(subMap.get("url")),subMap);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过配置文件获取对应网站的解析规则
     * @param novelSiteEnum
     * @return
     */
    public static Map<String, String> getContext(NovelSiteEnum novelSiteEnum){
        return CONTEXT_MAP.get(novelSiteEnum);
    }
}
